//
//  BDNewFriendViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/23.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDNewFriendViewController.h"
#import "BDFridentTableViewCell.h"
#import "BDFMDBTool.h"
#import "BDApplyFriendsModel.h"
#import "BDUserModel.h"
#import "BDTextFieldAlert.h"

@interface BDNewFriendViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *datasource;

@end

@implementation BDNewFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"申请与通知");
    [self requestDatasource];
    [self.tableView reloadData];
    
    [self binRAC];
}

- (void)binRAC{
    
}

- (void)requestDatasource{
    self.datasource = [BDFMDBTool queryWithClass:[BDApplyFriendsModel class]].mutableCopy;
    
    for (BDApplyFriendsModel *applyModel in self.datasource) {
        if (applyModel.yetToView.integerValue == 0) {
            [BDFMDBTool updateObject:applyModel condition:@"set yetToView = '1' where yetToView = '0'"];
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
}

#pragma mark - UITableViewDelegate
//设置编辑风格EditingStyle
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    //通过表视图是否处于编辑状态来选择是左滑删除，还是多选删除。
    if (tableView.editing) {
        //当表视图处于没有未编辑状态时选择多选删除
        return UITableViewCellEditingStyleDelete| UITableViewCellEditingStyleInsert;
    } else{
        //当表视图处于没有未编辑状态时选择左滑删除
        return UITableViewCellEditingStyleDelete;
    }
    
}
//根据不同的editingstyle执行数据删除操作（点击左滑删除按钮的执行的方法）
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        BDApplyFriendsModel *applyFriend = self.datasource[indexPath.row];
        [BDFMDBTool deleteWithObject:applyFriend];
        [self.datasource removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if(editingStyle == (UITableViewCellEditingStyleDelete| UITableViewCellEditingStyleInsert)) {
        
    }
    
}
//修改左滑删除按钮的title
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return ASLocalizedString(@"删除");
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 75;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID = @"cellID";
    BDNewFridentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[BDNewFridentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    BDApplyFriendsModel *applyModel = self.datasource[indexPath.row];
//    [MBManager showLoadingAlert:ASLocalizedString(@"请稍等")clickHidden:NO clickBlock:nil];
    [cell configeWithModel:applyModel clickButtonClick:^{
        if (applyModel.applyMode.integerValue == BDApplyFriendModeDefault) {
            [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
//            EMError *error = [[EMClient sharedClient].contactManager acceptInvitationForUsername:applyModel.user_id];
//            if (!error) {
//                NSString *url = [NSString stringWithFormat:@"%@users/%@", KBDBaseURL, applyModel.user_id];
//                NSString *headValid = [BDUserModel getHeaderValidation];
//
//                RACSignal *signal = [[BDNetworkingServer yy_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
//                [signal subscribeNext:^(id  _Nullable x) {
//                    BDFridentInfo *fridentInfo = [BDFridentInfo mj_objectWithKeyValues:x];
//                    NSArray *oldFriendArray = [BDFMDBTool queryWithClass:[BDFridentInfo class] condition:[NSString stringWithFormat:@"user_id = '%@'", fridentInfo.user_id]];
//                    if (oldFriendArray.count == 0) {
//                        [BDFMDBTool replaceWithObject:fridentInfo];
//                        //1.修改当前对象状态
//                        [BDFMDBTool updateObject:applyModel condition:[NSString stringWithFormat:@"set applyMode = '1' where user_id = '%@'", applyModel.user_id]];
//                        //2.修改界面显示
//                        [[NSNotificationCenter defaultCenter] postNotificationName:@"resreshFriendsList" object:nil];
//                        [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
//                        [self requestDatasource];
//                        [self.tableView reloadData];
////                        [MBManager hideAlert];
//                        [MBManager showBriefAlert:ASLocalizedString(@"添加成功")clickHidden:NO clickBlock:nil];
//                        [self performSelector:@selector(sendMessage:) withObject:fridentInfo.user_id afterDelay:2.0];
//                    }
//                }];
//
//                [signal subscribeError:^(NSError * _Nullable error) {
////                    [MBManager hideAlert];
//                    [MBManager showBriefAlert:ASLocalizedString(@"添加失败")clickHidden:NO clickBlock:nil];
//                }];
//
//            }else{
////                [MBManager hideAlert];
//                [MBManager showBriefAlert:ASLocalizedString(@"添加失败")clickHidden:NO clickBlock:nil];
//            }
        }else {
            [BDTextFieldAlert showWithTitle:ASLocalizedString(@"添加好友")placeHolder:ASLocalizedString(@"打个招呼吧")finishBlock:^(NSString *text) {
//                EMError *error = [[EMClient sharedClient].contactManager addContact:[NSString stringWithFormat:@"%@", applyModel.user_id] message:text];
//                if (!error) {
//                    [MBManager showBriefAlert:ASLocalizedString(@"请求已发送")clickHidden:NO clickBlock:nil];
//                    [BDFMDBTool updateObject:applyModel condition:[NSString stringWithFormat:@"set applyMode = '3' where user_id = '%@'", applyModel.user_id]];
//                    [self requestDatasource];
//                    [self.tableView reloadData];
//                }
            }];
        }
    }];
    return cell;
}

/*
 添加方和被添加方
 被添加方同意的时候，在会话中加入“已经是好友了，可以开始聊天了”
 
 */
- (void)sendMessage:(NSString *)aUser_id{
    //这里先留下吧，不知道怎么写，回头再测试
//    NSString *fromStr = [EMClient sharedClient].currentUsername;
//    NSString *text = ASLocalizedString(@"我已经同意了你的好友申请，现在开始聊天吧");
//    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
//    
//    EMMessage *message = [[EMMessage alloc] initWithConversationID:aUser_id from:fromStr to:aUser_id body:body ext:@{@"em_apns_ext":@{@"em_push_title":text}}];
//    message.chatType = EMChatTypeChat;
//    
//    [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:nil];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (NSMutableArray *)datasource{
    if (!_datasource) {
        self.datasource = [NSMutableArray array];
    }
    return _datasource;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
